﻿using System.Windows;
using CommunityToolkit.Mvvm.DependencyInjection;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using Syncfusion.UI.Xaml.Grid;
using Syncfusion.UI.Xaml.Grid.Helpers;
using TS2MP4.Locales;
using TS2MP4.ViewModels;
using MessageBox = iNKORE.UI.WPF.Modern.Controls.MessageBox;

namespace TS2MP4.Views;

/// <summary>
///     Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainView
{
    private readonly GridRowSizingOptions _gridRowResizingOptions = new();

    //To get the calculated height from GetAutoRowHeight method.
    private double _autoHeight = double.NaN;

    public MainView()
    {
        InitializeComponent();
        DataContext = Ioc.Default.GetRequiredService<MainViewModel>();
        WeakReferenceMessenger.Default.Register<MainView, ValueChangedMessage<string>, string>(
            this, "LoadFileErr", static (r, m) => { _ = MessageBox.Show(m.Value, Strings.LoadFileErr); });
    }

    private void SfDataGrid_QueryRowHeight(object sender, QueryRowHeightEventArgs e)
    {
        if (!SfDataGrid.GridColumnSizer.GetAutoRowHeight(e.RowIndex, _gridRowResizingOptions, out _autoHeight) ||
            _autoHeight <= 30) return;
        e.Height = _autoHeight;
        e.Handled = true;
    }

    private void Window_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        SfDataGrid.GetVisualContainer().RowHeightManager.Reset();
        SfDataGrid.GetVisualContainer().InvalidateMeasureInfo();
    }

    private void Window_Closed(object sender, EventArgs e)
    {
        WeakReferenceMessenger.Default.UnregisterAll(this);
    }
}